import { NextApiRequest, NextApiResponse } from 'next';
import { withIronSessionApiRoute } from 'iron-session/next';
import { ironOptions } from '@/config';
import { prepareConnection } from '@/db';
import { Article, Tag } from '@/db/entity';
import { EXCEPTION_ARTICLE } from '@/pages/api/config/codes';

const update = async (req: NextApiRequest, res: NextApiResponse) => {
  const { title = '', content = '', id, tagIds = [] } = req.body;
  const db = await prepareConnection();
  const articleRepo = db.getRepository(Article)
  const tagRepo = db.getRepository(Tag)

  const tags = await tagRepo.find({
    where: tagIds?.map((tagId: number) => ({ id: tagId })),
  })

  const newTags = tags.map((tag) => {
    tag.article_count += 1
    return tag
  })

  const article = await articleRepo.findOne({
    where: {
      id,
    },
    relations: ['user'],
  })

  if (!article) {
    res.status(200).json({ ...EXCEPTION_ARTICLE.NOT_FOUND });
    return;
  }

  article.title = title;
  article.content = content;
  article.update_time = new Date();
  article.tags = newTags

  const articleResult = await articleRepo.save(article)

  if (articleResult) {
    res.status(200).json({ data: articleResult, code: 200, msg: '更新成功' });
  } else {
    res.status(200).json({ ...EXCEPTION_ARTICLE.PUBLISH_FAILED });
  }
};

export default withIronSessionApiRoute(update, ironOptions);
